#!/usr/local/bin/perl

use lib "/home/sgetest/lib";
use TIGR::HTCRequest;
use TIGR::HTCUtils;
use Log::Log4perl;

my $log_conf = q~
log4perl.rootLogger=DEBUG, client
log4perl.appender.client=Log::Log4perl::Appender::File
log4perl.appender.client.mode=append
log4perl.appender.client.layout=Log::Log4perl::Layout::PatternLayout
log4perl.appender.client.layout.ConversionPattern=%H [%d{MM/dd HH:mm}] %p %M - %m%n
~;


# setup logging
#
my $logfile = "/usr/local/scratch/$ENV{USER}/arr-job-file/submit.log";
$log_conf .= "log4perl.appender.client.filename=$logfile\n";

Log::Log4perl::init(\$log_conf);
my $logger = Log::Log4perl->get_logger(__PACKAGE__);
$logger->info("Starting file array job test.");

# Before starting the test, count the perl processes
my $proc_cnt = TIGR::HTCUtils->get_perl_process_count();
#$logger->info("Active perl process count is : $proc_cnt");
print "Active perl process count is : $proc_cnt \n";
if ($proc_cnt > 20) {
        #print "Active perl process count exceeded max limit of 20. Skipping the launch of new test..\n";
        $logger->info("Active perl process count exceeded max limit of 20. Skipping the launch of new test..");
	TIGR::HTCUtils->log_test_skip("test_htc_file");
        exit(1);
}

TIGR::HTCUtils->log_test_start("test_htc_file");
my $request = TIGR::HTCRequest->new(group => "antware",
				    initialdir => "/usr/local/scratch/$ENV{USER}/arr-job-file");

#command to run
$request->set_command("/usr/local/scratch/$ENV{USER}/arr-job-file/test.sh");

# file with list of args
$request->add_param({ key => "--file", value => "/usr/local/scratch/$ENV{USER}/arr-job-file/file_test.txt", type  => "FILE",} );

$request->set_output("/usr/local/scratch/$ENV{USER}/arr-job-file/htc_test_file.\$(Index).out");
$request->set_error("/usr/local/scratch/$ENV{USER}/arr-job-file/htc_test_file.\$(Index).err");

# do you need to copy the enviroment
$request->set_getenv(1);

# submit job
my $id = $request->submit();

my $xx = $request->to_xml();
print $xx;

print " Request id was $id \n";

# wait for job finish
$request->wait_for_request();

my $message = $request->get_message();
$logger->info("Finished file array job test. Message: $message");
my $state = $request->get_state();
if($request->get_state() eq "FAILURE") {
    print " failed: $message \n";
    exit(1);
} elsif ($request->get_state() eq "FINISHED") {
    print " Request finished correctly\n";
} else {
    print " Request finished with state $state and $message \n";
}

TIGR::HTCUtils->log_test_finish("test_htc_file");
print "command finished\n";
exit(0);
